﻿@model IEnumerable<SweetSurvey.Models.Survey>
@using SweetSurvey.Models.Repositories;
@{
    ViewBag.Title = "Surveys";
    Layout = "~/Views/Shared/_AdministratorLayout.cshtml";
}

@{
    var grid = new WebGrid(Model, rowsPerPage: 20);
    @grid.GetHtml(
        columns: grid.Columns(
            grid.Column(format: @<text><input type='checkbox' ss:survey-id='@item.Id'/></text>, style: "text-align-left"),
            grid.Column(format: @<text><a href="@Url.Action("Report", "Survey", new { id = item.Id })" target="_blank">@item.Title</a></text>, header: "Title"),
            grid.Column("EditorId", "Editor"),
            grid.Column("DateCreated", "Creation Date"),
            grid.Column(header: "Participator(s)", format: (item) => (new ParticipatorRepository()).GetParticipatorCountBySurveyId(item.Id))
        ),
        mode: WebGridPagerModes.FirstLast|WebGridPagerModes.NextPrevious|WebGridPagerModes.Numeric,
        firstText: "First Page",
        lastText: "Last Page",
        previousText: "Previous Page",
        nextText: "Next Page",
        tableStyle: "full-width",
        selectedRowStyle: "gray-background"
    )
}
<button onclick="selectAll()">Select All</button>
<button onclick="deleteSelectedSurveys()">Delete Selected Survey(s)</button>
<script type="text/javascript">
    function deleteSelectedSurveys() {
        var objects = getAllCheckboxes().filter(':checked');
        if (objects.length == 0) { alert('No item is selected.'); return; }
        if (!confirm('Are you sure?')) { return; }
        var surveyIds = [];
        objects.each(function () { surveyIds.push($(this).attr('ss:survey-id')); });
        $.post(
            '@Url.Action("DeleteSurveys", "Administrator")',
            { surveyIds: JSON.stringify(surveyIds) },
            function (response) {
                if (response == 'success') { window.location.reload(); }
                else { alert(response); }
            }
        );
    }
    function getAllCheckboxes() {
        return $('input').filter(function () {
            return $(this).attr('ss:survey-id');
        });
    }
    function selectAll() {
        getAllCheckboxes().attr('checked', true).trigger('change');
    }
    $(function () {
        getAllCheckboxes().change(function () {
            var row = $(this).parent().parent();
            if ($(this).attr('checked')) { row.css('background-color', '#e0e0e0'); }
            else { row.css('background-color', 'white'); }
        });
    });
</script>